package com.deng.crowd.mvc.handler;

import com.deng.crowd.entity.Role;
import com.deng.crowd.service.api.AdminService;
import com.deng.crowd.service.api.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class AssignHandler {

    @Autowired
    private RoleService roleService;

    @Autowired
    private AdminService adminService;

    @RequestMapping("/assign/to/page.html")
    public String toAssignPage(@RequestParam("adminId") Integer adminId, Model model) {
        // 得到对应当前adminId未被分配的角色（Role）List
        List<Role> assignedRoleList = roleService.getAssignedRole(adminId);
        // 得到对应当前adminId已被分配的角色（Role）List
        List<Role> unAssignedRoleList = roleService.getUnAssignedRole(adminId);
        // 将已选择的、未选择的放入modelMap
        model.addAttribute("assignedRoleList", assignedRoleList);
        model.addAttribute("unAssignedRoleList", unAssignedRoleList);
        // 请求转发到assign-role.jsp
        return "assign-role";
    }

    @RequestMapping("assign/do/role/assign.html")
    public String saveAdminRoleRelationship(
            @RequestParam("adminId") Integer adminId,
            @RequestParam("pageNum") Integer pageNum,
            @RequestParam("keyword") String keyword,
            // 允许roleIdList为空（因为可能已分配的被清空）
            @RequestParam(value = "roleIdList", required = false) List<Integer> roleIdList
    ) {
        // 调用service层方法
        adminService.saveAdminRoleRelationship(adminId, roleIdList);
        //重定向（减少数据库操作）返回信息页
        return "redirect:/admin/get/page.html?pageNum="+pageNum+"&keyword="+keyword;
    }
}
